﻿using AutoMapper;
using Domain.Entity.zct;
using Domain.IRepository;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Application.UserRoleService
{
    public class UserRoleService : IUserRoleService
    {
        private readonly IUserRoleRepository userroleRepository;
        private readonly IRoleRepository roleRepository;
        private readonly IMapper mapper;

        public UserRoleService(IUserRoleRepository userroleRepository, IMapper mapper ,IRoleRepository roleRepository)
        {
            this.roleRepository = roleRepository;
            this.userroleRepository = userroleRepository;
            this.mapper = mapper;
        }

        public Task<List<UserRole>> GetAll()
        {
            return userroleRepository.GetAll();
        }

        public async Task<List<UserRolesDto>> GetAllUserRolesAsync()
        {
            try
            {
                // 获取用户角色集合
                var userRoles = await userroleRepository.GetAll();

                // 获取角色集合
                var roles = await roleRepository.GetAll();

                // 将角色ID映射到角色名称
                var roleMap = roles.ToDictionary(r => r.Role_id, r => r.Role_name);

                // 按用户ID分组并拼接角色
                var result = userRoles
                    .GroupBy(ur => ur.User_id)
                    .Select(group => new UserRolesDto
                    {
                        User_id = group.Key,
                        RoleIds = string.Join("-", group.Select(ur => ur.Role_id.ToString())),
                        RoleNames = string.Join("-", group.Select(ur => roleMap[ur.Role_id]))
                    })
                    .ToList();

                return result;
            }
            catch (Exception ex)
            {
                Console.WriteLine($"Error occurred: {ex.Message}");
                throw;
            }
        }

        public async Task<UpdateUserRoleDto> Getuid(int uid)
        {
            try
            {
                // 1. 获取用户的所有角色关联记录
                List<UserRole> userRoles = await userroleRepository.Getuid(uid);

                // 2. 提取角色ID集合
                int[] roleIds = userRoles.Select(ur => ur.Role_id).ToArray();

                // 3. 获取所有角色信息（使用批量查询提高效率）
                var allRoles = await roleRepository.GetAll();

                // 4. 构建角色ID到角色名称的映射字典
                var roleMap = allRoles.ToDictionary(r => r.Role_id, r => r.Role_name);

                // 5. 创建并填充DTO对象
                return new UpdateUserRoleDto
                {
                    RoleIds = roleIds,
                    RoleNames = roleIds
                        .Where(id => roleMap.ContainsKey(id)) // 确保角色存在
                        .Select(id => roleMap[id])
                        .ToArray()
                };
            }
            catch (Exception ex)
            {
                Console.WriteLine($"Error in Getuid: {ex.Message}");
                throw; // 根据实际需求决定是否抛出异常
            }
        }
    }
}